# encoding:utf8
import os,sys
import json
import importlib
import smtplib
from email.mime.text import MIMEText
import datetime,time
import traceback

#*****************
# 装饰器，实时应用代码修改
#*****************
def apply_source_change(func):
    def inner(*args,**kwargs):
        file_modify_record = 'file_modify_time.json'
        try:
            with open(file_modify_record) as afile:
                modify_time = json.load(afile)
        except:
            modify_time={}
        #print(os.path.curdir)
        #print(os.path.dirname(os.path.abspath(__file__)))

        # 遍历当前文件夹及子文件夹
        to_search = []
        base_route = os.path.dirname(__file__)  #基本路径
        to_search.append(base_route)
        filetype='.py'  #跟踪文件类型
        while len(to_search) >0:
            cur = to_search.pop()
            cur_modify_time = os.path.getmtime(cur)  # 获取文件的修改时间
            last_modify_time = modify_time.get(cur)
            if cur_modify_time != last_modify_time:
                if os.path.isfile(cur) and cur.endswith(filetype):
                    modify_time[cur] = cur_modify_time
                    mod_name = cur[len(base_route)+1:-1*len(filetype)].replace('/','.') #根据基本目录，计算module的名称
                    module = sys.modules.get(mod_name)
                    if module:
                        importlib.reload(module)    #被修改时，重载module
                        print('reload %s'%mod_name)
                # 如果是目录且不是隐藏目录
                elif os.path.isdir(cur) and not cur.split('/')[-1].startswith('.'):
                    file_list = os.listdir(cur)
                    for afile in file_list:
                        abs_file = cur + '/' +afile
                        to_search.append(abs_file)
        with open(file_modify_record,'w') as open_file:
            json.dump(modify_time,open_file)
        ret = func(*args,**kwargs)
        return ret
    return inner

#发送邮件
class Mailman(object):
    def __init__(self,msg_from,msg_to,passwd,server,server_port,subject = "服务器监控"):
        self.msg_from = msg_from
        self.msg_to = msg_to
        self.passwd = passwd
        self.subject = subject
        self.server = server
        self.server_port = server_port

    def mail(self,message):
        # 主题
        #content = "这是我使用python smtplib及email模块发送的邮件"# 正文
        msg = MIMEText(message)
        msg['Subject'] = self.subject
        msg['From'] = self.msg_from
        msg['To'] = self.msg_to
        s = None
        try:
            s = smtplib.SMTP_SSL(self.server, self.server_port) # 邮件服务器及端口号
            s.login(self.msg_from, self.passwd)
            s.sendmail(self.msg_from, self.msg_to, msg.as_string())
            print("发送成功")
        except:
            print("发送失败")
        finally:
            s.quit()
#***********************
# 装饰器，对函数异常进行捕获处理，发送邮件通知
#**********************
def error_reporter(ip,program_name):
    def middle(func):
        def inner(*args,**kwargs):
            try:
                ret = func(*args,**kwargs)
                return ret
            except (KeyboardInterrupt):
                raise KeyboardInterrupt
            except:
                message = traceback.format_exc()
                mail_from = '565288765@qq.com'
                mail_pwd = 'guzoxgunvixlbcii'
                mail_server = 'smtp.qq.com'
                mail_server_port = 465
                mail_to = '565288765@qq.com'
                subject ='%s %s error'%(ip,program_name)
                mm = Mailman(mail_from, mail_to, mail_pwd, mail_server, mail_server_port, subject)
                message = '%s location(%s) program(%s): %s'%(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),ip,program_name,message)
                #print(message)
                mm.mail(message)
        return inner
    return middle

#********************
#
#********************
def speed_evalutor(func):
    def inner(*args,**kwargs):
        start_time = time.time()
        ret = func(*args,**kwargs)
        end_time = time.time()
        cost = end_time-start_time
        print(cost)
        return ret
    return inner
